package guicommon;

import java.nio.CharBuffer;

public class Header {

    static final int HEADER_LENGTH = 12;

    private int bodyLength;

    private MessageType msgType;

    private int msgCode;

    Header(char[] headerBuffer) {        
        int length = Integer.SIZE / 8;
        int index = 0;
        bodyLength = GetIntFromCharArray(headerBuffer, index, length);
        index += length;
        msgType = MessageType.FromInt(GetIntFromCharArray(headerBuffer, index, length));
        index += length;
        msgCode = GetIntFromCharArray(headerBuffer, index, length);
    }

    private Header() {
        bodyLength = 0;
    }

    private static int GetIntFromCharArray(char[] array, int index, int length) {
        String str = new String(array, index, length);
        return Integer.valueOf(str);
    }

    public int GetBodyLength() {
        return bodyLength;
    }

    public MessageType GetMessageType() {
        return msgType;
    }

    public int GetMessageCode() {
        return msgCode;
    }

    public CharSequence ToCharSequence(CharBuffer buffer) {
        AppendInteger(buffer, bodyLength);
        AppendInteger(buffer, msgType.GetIndex());
        AppendInteger(buffer, msgCode);
        return buffer;
    }

    private static void AppendInteger(CharBuffer buffer, Integer number) {
        String numberString = number.toString();
        for (int i = numberString.length(); i < 4; i++) {
            buffer.append('0');
        }
        buffer.put(numberString);
        /*final int iterationCount = Integer.SIZE / Byte.SIZE;
        for (int i = 0; i < iterationCount; i++) {
            byte current = number.byteValue();
            buffer.append((char)current);
            number = number >> Byte.SIZE;
        }*/
    }

    public void IncrementLength(int incrementMean) {
        bodyLength += incrementMean;
    }

    public static Header FromType(Class type, int code) {
        Header result = new Header();
        result.msgCode = code;
        result.msgType =
                MessageFactory.GetInstance().GetMessageTypeFromMessage(type);
        return result;
    }
}
